import {
  Button,
  Drawer,
  Form,
  Icon,
  Input,
  Modal,
  Popover,
  Space
} from "@bytedance/mona-ui"
// import productTopItemStyle from "@Styles/productTopItemStyle.scss?inline"
import type {
  PlasmoCSConfig,
  PlasmoGetInlineAnchor,
  PlasmoGetStyle,
  PlasmoMountShadowHost
} from "plasmo"
import React, { useState } from "react"
import { Provider } from "react-redux"

import { PersistGate } from "@plasmohq/redux-persist/integration/react"
import { Agreement } from "@Utils/addConfigFuncs"
import { persistor, store, useAppDispatch, useAppSelector } from "~store"
// useAppSelector
import {
  getCouponListAllData,
  getDetailNewUserGiftAllData,
  getDiscountActivity,
  getGoodsAsync,
  getPromotionListFlashAllData,
  getSurpriseTicketLisAllData,
  showPriceInfo
} from "~store/controller/jinritemaiProduct"
import {
  getshopFreightTemplateAsync,
  getUserShopID,
  setUserPhoneFun,
  setUserPhoneModal,
  shopLogin,
  testWtServer
} from "~store/controller/jinritemaiShops"
import { clearFlowWeiStatus, weiguijianceContent } from "~store/controller/funcTabs"

// setactivityToolType

// export const getStyle: PlasmoGetStyle = () => {
//   const style = document.createElement("style")
//   style.textContent = productTopItemStyle
//   return style
// }

export const config: PlasmoCSConfig = {
  matches: ["https://fxg.jinritemai.com/*"]
}

export const getInlineAnchor: PlasmoGetInlineAnchor = async () => {
  const getItemr = document.querySelector(
    "[class*=index_middle-bar-wrapper] > [class*=style_renderMiddleStyle]"
  ) || document.querySelector(
    "[class*=style-module_middle-bar-wrapper] > [class*=style_renderMiddleStyle]"
  )
  return getItemr
}
export const mountShadowHost: PlasmoMountShadowHost = ({
  shadowHost,
  anchor,
  mountState
}) => {
  const addchi = document.querySelector(
    "[class*=style_renderMiddleStyle] > [class*=style_leftButtonGroup]"
  )
  addchi && anchor?.element?.insertBefore(shadowHost, addchi.nextSibling)
  mountState?.observer?.disconnect()
}

export const getShadowHostId = () => "product-top-item-id"

const TaberTopBut = () => {
  const dispatch = useAppDispatch()
  const [showShopPriteStatus, setShopDrawer] = useState(false)
  const [userphone, setuserphon] = useState("")
  const [isError, setIsError] = useState(false)
  const addUserPhone = useAppSelector(
    (start) => start.jinritemaiShops.addUserPhone
  )
  const [form] = Form.useForm()
  //   const uer = useAppSelector((state) => state.jinritemaiProduct.activityToolType)
  return (
    <Space className="butenconter" size={12}>
      {false && <Popover
        trigger="click"
        content={
          <Space direction="vertical">
            <div>
              因近期抖店优惠券，活动等规则调整，查看策略功能暂时停止使用
              <br />
              待规则调整完毕后上线，给您造成不便敬请谅解
            </div>
            <div
              className="moter"
              style={{
                width: "100%",
                display: "flex",
                justifyContent: "flex-end"
              }}>
              {/* <Button
                size="mini"
                type="primary"
                onClick={() => {
                    setshowErrCoupeters(false)
                }}>
                知道了
              </Button> */}
            </div>
          </Space>
        }
      // visible={showErrCoupeters}
      >
        <Button
          size="small"
          type="primary"
        // onClick={() => dispatch(showPriceInfo("all"))}
        >
          一键转换价格
        </Button>
      </Popover>}
      <Space>
        <Button
          size="small"
          type="primary"
          onClick={() => {
            Agreement().then(() => {
              dispatch(showPriceInfo("all"))
            })

          }}
        >
          一键转换价格
        </Button>
        <Button size="small" onClick={() => {
          dispatch(clearFlowWeiStatus(true))
        }}>
          清理无流量
        </Button>
        <Button size="small" type="secondary" icon={<Icon type="AiDrawIcon"></Icon>} onClick={() => {
          dispatch(weiguijianceContent(''))
        }}>
          违规检测
        </Button>
      </Space>

      {/* <Button
        size="small"
        type="primary"
        onClick={() => dispatch(showPriceInfo("all"))}>
        一键转换价格

      </Button> */}
      {/* <Button size="small" onClick={() =>  dispatch(getUserShopID(''))}>
        测试请求异步
      </Button>  */}
      {/* <Button size="small" onClick={() => setShopDrawer(true)}>
        全部价格转换0
      </Button>
      <Button size="small" onClick={() =>  dispatch(getshopFreightTemplateAsync(''))}>
        测试请求优惠券
      </Button>
      <Button size="small" onClick={() =>  dispatch(getGoodsAsync(''))}>
        测试请求异步
      </Button> */}
      {/* <Button
        size="small"
        onClick={() => {
          // store.dispatch(setToken())
          // 获取限时限量购活动商品列表
          store.dispatch(getGoodsAsync(""))
          // 获取满减活动商品列表
          store.dispatch(getDiscountActivity(""))
          // 获取新人礼金商品列表
          store.dispatch(getDetailNewUserGiftAllData(""))
          // 惊喜券
          store.dispatch(getSurpriseTicketLisAllData(""))
          // 优惠券
          store.dispatch(getCouponListAllData(""))
          // 运费模板
          store.dispatch(getshopFreightTemplateAsync(""))
          // 拼团
          store.dispatch(getPromotionListFlashAllData(""))
        }}>
        测试请求
      </Button>
      <Button size="small" onClick={() => {
         dispatch(getDetailNewUserGiftAllData(''))
      }}>
        测试请求WEBSERVER666
      </Button>
      <Button size="small" onClick={() =>  dispatch(shopLogin(''))}>
        测试请求shop_id
      </Button>
      <Button size="small" onClick={() =>  dispatch(getGoodsAsync(''))}>
        测试请求异步
      </Button>
      <Button size="small" onClick={() =>  dispatch(getSurpriseTicketLisAllData(''))}>
        测试惊喜券
      </Button> */}
      {/* <Button size="small" onClick={() => dispatch(getUserShopID(""))}>
        测试获取shopid
      </Button> */}
      <Drawer
        title="最终成交价转换结果"
        placement="right"
        closable
        onOk={() => setShopDrawer(false)}
        onCancel={() => setShopDrawer(false)}
        visible={showShopPriteStatus}
      />
      <Modal
        size="small"
        // addUserPhone
        // 要求用户填写手机号
        visible={false}
        title="请完善您的个人信息"
        okText=" 确定"
        cancelText=" 取消"
        onCancel={() => dispatch(setUserPhoneModal(false))}
        onOk={() => dispatch(setUserPhoneFun(userphone))}>
        {/* dispatch(setUserPhoneFun(userphone)) */}
        <Form
          layout="horizontal"
          name="userPhone"
          onFinish={(data) => {
            //  console.log('结果：', data);
          }}
          form={form}>
          <Form.Item
            name="手机号"
            label="手机号"
            validateStatus={isError ? "error" : "success"}
            rules={[{ required: true, message: "请输入您的手机号！" }]}
            help={isError ? "请输入您的正确手机号！" : null}>
            <Input
              placeholder="请输入手机号"
              onChange={(e) => {
                setuserphon(e.target.value)
                //   setIsError(true)
              }}
            />
          </Form.Item>
        </Form>
      </Modal>
      {/* <input onChange={(e) => dispatch(setactivityToolType(e.target.value))} value={uer}></input> */}
    </Space>
  )
}

const PlasmoInline = () => {
  return (
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        <TaberTopBut />
      </PersistGate>
    </Provider>
  )
}

export default PlasmoInline

// import type {
//     PlasmoCSConfig,
//     PlasmoCSUIJSXContainer,
//     PlasmoCSUIProps,
//     PlasmoRender
//   } from "plasmo"
//   import type { FC } from "react"
//   import { createRoot } from "react-dom/client"

//   export const config: PlasmoCSConfig = {
//     matches: ["https://fxg.jinritemai.com/*"]
//   }

// //   export const getRootContainer = () =>
// //     new Promise((resolve) => {
// //       const checkInterval = setInterval(() => {
// //         const rootContainerParent = document.querySelector(`[href="/docs"]`)
// //         console.log('ee')
// //         if (rootContainerParent) {
// //           clearInterval(checkInterval)
// //           const rootContainer = document.createElement("div")

// //           rootContainerParent.appendChild(rootContainer)
// //           resolve(rootContainer)
// //         }
// //       }, 137)
// //     })
//     export const getRootContainer = () =>
//     new Promise((resolve) => {
//       const checkInterval = setInterval(() => {
//         // const tabTitle = document.querySelector('.ecom-g-table-thead')
//         const rooTtableTitle = document.getElementsByTagName("th")
//         if (rooTtableTitle && rooTtableTitle.length) {
//           for (let i = 0; i <= rooTtableTitle.length; i++) {
//             const spanlist = rooTtableTitle[i].innerText
//             if (spanlist === "价格") {
//               clearInterval(checkInterval)
//               const rootContainer = document.createElement("div")

//               rooTtableTitle[i].appendChild(rootContainer)
//             //   const rootContainer = document.createElement("th")
//             //   rootContainer.className = "ecom-g-table-cell"
//             //   rooTtableTitle[i].parentNode.insertBefore(
//             //     rootContainer,
//             //     rooTtableTitle[i].nextSibling
//             //   )
//               resolve(rootContainer)
//               break
//             }
//           }
//         }
//       }, 137)
//     })
//   const PlasmoOverlay: FC<PlasmoCSUIProps> = () => {
//     return (
//       <span
//         style={{
//           borderRadius: 4,
//           background: "yellow",
//           padding: 4,
//           position: "absolute",
//           top: '-23px',
//           right: '-121px',
//           transform: "translateY(-24px) translateX(42px)"
//         }}>
//         CSUI ROOT CONTAINER 4
//       </span>
//     )
//   }

//   export const render: PlasmoRender<PlasmoCSUIJSXContainer> = async ({
//     createRootContainer
//   }) => {
//     const rootContainer = await createRootContainer()
//     const root = createRoot(rootContainer)
//     setTimeout(_=>{
//       root.render(<PlasmoOverlay />)
//     }, 3000)
//   }

//   export default PlasmoOverlay
